//
//  SearchLocalTool.m
//  Trunk
//
//  Created by xiaowu on 2017/7/20.
//
//

#import "SearchLocalTool.h"

@implementation SearchLocalTool

+ (NSString *)cacheDiskPath {
    NSString *path = [NSHomeDirectory() stringByAppendingPathComponent:@"Library/SearchCache"];
    return (path);
}
+ (NSString *)getCachePath {
    return [NSString stringWithFormat:@"LocalSearchCache"];
}
+ (void)saveCache:(NSString *)savePath cache:(id)cache {
    if(!TextIsNotNil(savePath) || !cache) {
        return;
    }
    
    NSData *data = [NSKeyedArchiver archivedDataWithRootObject:cache];
    NSString *filePath = [self cacheDiskPath];
    NSString *path = [filePath stringByAppendingPathComponent:[savePath md5]];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    if([fileManager isExecutableFileAtPath:path]) {
        NSError *error = nil;
        if([fileManager removeItemAtPath:path error:&error]) {
            NSLog(@">>>remove file failed:%@", error.debugDescription);
        }
        return;
    }
    if(![fileManager fileExistsAtPath:filePath]) {
        if(![fileManager createDirectoryAtPath:filePath withIntermediateDirectories:YES attributes:nil error:nil]) {
            NSLog(@">>>carete directory failed at path:%@", filePath);
        }
    }
    if(![fileManager createFileAtPath:path contents:data attributes:nil]) {
        NSLog(@">>>carete file failed at path:%@", path);
    }
}
+ (id)returnCache:(NSString *)savePath {
    if(!savePath) {
        return (nil);
    }
    
    NSString *filePath = [self cacheDiskPath];
    NSString *path = [filePath stringByAppendingPathComponent:[savePath md5]];
    NSData *data = [NSData dataWithContentsOfFile:path];
    if(!data || ![data isKindOfClass:[NSData class]]) {
        return (nil);
    }
    id obj = [NSKeyedUnarchiver unarchiveObjectWithData:data];
    return (obj);
}

+ (NSMutableArray *)getSearchLocalCache {
    NSString *path = [self getCachePath];
    id obj = [self returnCache:path];
    if ([obj isKindOfClass:[NSArray class]]) {
        return obj;
    } else {
        return [NSMutableArray array];
    }
}

+ (void)saveSearchLocalCache:(NSMutableArray *)arr {
    [self saveCache:[self getCachePath] cache:arr];
}

@end
